import { PPTContents, PPTDataJson, PPTHomeEndPage, PPTPage, PPTPageList, PPTTitle, ServerData } from '@/models/ai-ppt'
import { ref, type Ref } from 'vue'

export const pptOutlineKey: Ref<string> = ref('ai-ppt-outline-mk-key')
export const pptThemeInputKey: Ref<string> = ref('ai-ppt-input-theme-key')
export const pptFileIdKey: Ref<string> = ref('ai-ppt-file-id-key')
export const pptFileContentKey: Ref<string> = ref('ai-ppt-file-Content-key')

type HomeEnd = 'home' | 'end'

const formatMarkdownHomeEnd = (line: string, type: HomeEnd = 'home'): PPTHomeEndPage => {
  try {
    line = line.slice(2)
    let title: string,
      sub_title: string
    if (line.includes('-')) {
      [title, sub_title] = line.split('-', 2)
    } else if (line.includes('——')) {
      [title, sub_title] = line.split('——', 2)
    }
    return {
      type,
      title: title.trim(),
      sub_title: sub_title ? sub_title.trim() : '',
    }
  } catch (e) {
    throw new Error('Markdown 解析成 Json 失败！' + e)
  }
}

const formatNumberTitle = (line: string): string => {
  try {
    const lineArr = line.split(' ')
    const first = lineArr.shift()
    let content: string
    if (!/^\d/.test(first)) {
      lineArr.unshift(first)
    }
    content = lineArr.join(' ')
    return content
  } catch (e) {
    throw new Error('Markdown 解析成 Json 失败！' + e)
  }
}

const formatMarkdownTitle = (line: string): PPTTitle => {
  line = line.slice(3)
  const content = formatNumberTitle(line)
  return {
    type: 'title',
    title_title: content,
    title_sub_title: '',
    pages: [],
  }
}

const appendPage = (page_title: string, pageList: PPTPageList[], data: PPTDataJson[]) => {
  if (page_title) {
    const pageItem: PPTPage = {
      type: 'page',
      page_title: page_title ? page_title : '',
      list: [...pageList],
    }
    const last = data[data.length - 1]
    if (last.type === 'title') {
      last.pages.push(pageItem)
    }
    pageList = []
  }
  return pageList
}

export const markdownToJson = (content: string, outline: boolean = true): PPTDataJson[] => {
  let lines: string[] = content.split('\n')
  lines = lines.filter(item => !!item.trim())
  const data: PPTDataJson[] = []
  let pageList: PPTPageList[] = []
  let page_title: string = ''
  const pageListItem: PPTPageList = {
    type: 'page_sub_title',
    page_sub_title: '',
    page_content: '',
  }
  lines.forEach((line, key) => {
    if (line.startsWith('# ')) {  // 首页
      data.push(formatMarkdownHomeEnd(line))
    } else if (line.startsWith('## ')) { // 标题页
      if (pageList.length) {
        pageList = appendPage(page_title, pageList, data)
      }
      data.push(formatMarkdownTitle(line))
    } else if (line.startsWith('### ')) {
      if (pageList.length) {
        pageList = appendPage(page_title, pageList, data)
      }
      line = line.slice(4)
      page_title = formatNumberTitle(line)
    } else if (line.startsWith('#### ')) {
      line = line.slice(5)
      pageListItem.page_sub_title = formatNumberTitle(line)
      if (!lines[key + 1] || !lines[key + 1].startsWith('- ')) {
        pageList.push({ ...pageListItem })
      }
    } else if (line.startsWith('- ')) {
      line = line.slice(2)
      pageListItem.page_content = line
      if (!lines[key + 1] || !lines[key + 1].startsWith('- ')) {
        pageList.push({ ...pageListItem })
      }
    }
  })
  if (page_title) {
    appendPage(page_title, pageList, data)
  }
  if (!outline) {
    const line: string = '# 致谢 - 感谢大家的关注与支持，请提出问题参与讨论'
    data.push(formatMarkdownHomeEnd(line, 'end'))
  }
  return data
}

export const jsonToMarkdown = (data: PPTDataJson[]): string => {
  let markdown: string = '\n'
  data.forEach((item, index) => {
    if (item.type !== 'title') {
      markdown += `# ${item.title} - ${item.sub_title}\n`

    } else {
      markdown += `## ${index} ${item.title_title}\n`
      item.pages?.forEach((page, i) => {
        markdown += `### ${index}.${i + 1} ${page.page_title}\n`
        page.list.forEach((pl, k) => {
          markdown += `#### ${index}.${i + 1}.${k + 1} ${pl.page_sub_title}\n`
        })
      })
    }
    markdown += `\n`
  })
  return markdown
}

export const markdownJsonToServer = (data: PPTDataJson[]): ServerData[] => {
  const serverData: ServerData[] = []

  const contents: PPTContents = {
    type: 'contents',
    list: [],
  }

  data.forEach((item, i) => {
    if (item.type !== 'title') {
      serverData.push(item)
    } else {
      contents.list.push(item.title_title)
      serverData.push({
        type: 'title',
        title_title: item.title_title,
        title_sub_title: '',
        title_number: (i <= 9 ? '0' : '') + i,
      })
      item.pages?.forEach(page => {
        serverData.push({ ...page })
      })
    }
  })

  serverData.splice(1, 0, { ...contents })
  serverData.push({
    type: 'end',
    title: '致谢',
    sub_title: '感谢大家的关注与支持，请提出问题参与讨论',
  })

  return serverData
}